package by.parfen.game.atrash.service.etc.impl;

import java.io.StringReader;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;

import by.parfen.game.atrash.service.etc.WebsocketMessageCoder;
import by.parfen.game.datamodel.etc.WebsocketMessage;

public class WebsocketMessageCoderImpl implements WebsocketMessageCoder {

	@Override
	public JsonObject encode(WebsocketMessage message) {
		JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
		jsonBuilder.add("subject", message.getSubject());
		jsonBuilder.add("content", message.getContent());
		JsonObject jsonObject = jsonBuilder.build();
		return jsonObject;
	}

	@Override
	public WebsocketMessage decode(JsonObject jsonMessage) {
		JsonObject jsonObject = Json.createReader(new StringReader(jsonMessage.toString())).readObject();
		WebsocketMessage message = new WebsocketMessage();
		message.setSubject(jsonObject.getString("subject"));
		message.setContent(jsonObject.getString("content"));
		return message;
	}

}
